#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "msfs.h"
#include "readin.h"

char arg_buf[BUF_SIZE];

static char line_buf[BUF_SIZE];
static unsigned int line_len;
static char *buf_p;

static enum command_type arg_validation(char *arg, enum command_type ret)
{
    char *start = arg;

    while (isspace(*start) && *start != '\0') {
        start++;
    }
    /* must have a argument */
    if (strlen(start) == 0) {
        return CMD_UNVALID;
    }
    /* only argument of load has the possibility of having space within it */
    if (ret != CMD_LOAD && strchr(start, ' ') != 0) {
        return CMD_UNVALID;
    }
    strncpy(arg_buf, start, BUF_SIZE);
    return ret;
}

static char *trim_space(char *str)
{
    unsigned int len;
    char *start, *end;

    if (0 == (len = strlen(str))) {
        return str;
    }

    start = str;
    end = str + len - 1;
    while (isspace(*start) && *start != '\0') {
        start++;
    }
    while (isspace(*end) && end >= start) {
        end--;
    }
    *(++end) = '\0';
    return start;
}

enum command_type read_command(void)
{
    char *arg;
    enum command_type type;

    if (fgets(line_buf, BUF_SIZE, stdin) == NULL) {
        return CMD_UNVALID;
    }
    buf_p = trim_space(line_buf);
    line_len = strlen(line_buf);

    /* check for command ls */
    if (NULL == (arg = strchr(buf_p, ' '))) {
        if (strcmp(buf_p, "ls") == 0) {
            return CMD_LS;
        }
        else if (strcmp(buf_p, "exit") == 0) {
            return CMD_EXIT;
        }
        else {
            return CMD_UNVALID;
        }
    }
    /* check for load, cd, and rm, they must have at most one argument */
    else {
        *(arg++) = '\0';
        if (strcmp(buf_p, "load") == 0) {
            type = CMD_LOAD;
        }
        else if (strcmp(buf_p, "cd") == 0) {
            type = CMD_CD;
        }
        else if (strcmp(buf_p, "rm") == 0) {
            type = CMD_RM;
        }
        else {
            return CMD_UNVALID;
        }
        return arg_validation(arg, type);
    }
}
